<?php

namespace App\Http\Controllers;

use App\Models\Ad;
use Illuminate\Http\Request;
use GuzzleHttp\Client;

class AdController extends Controller
{
    /**
     * 获取广告配置
     */
    public function getConfig(Request $request)
    {
        // 获取位置参数
        $position = $request->input('position');
        
        // 查询有效的广告
        $ads = Ad::where('status', Ad::STATUS_ENABLED)
            ->where('start_time', '<=', time())
            ->when($position, function ($query) use ($position) {
                return $query->where('position', $position);
            })
            ->when(!$position, function ($query) {
                return $query->where('position', Ad::POSITION_HOME);
            })
            ->where(function ($query) {
                return $query->where('end_time', 0)->orWhere('end_time', '>=', time());
            })
            ->orderBy('display_order', 'asc')
            ->get();
        
        // 增加浏览次数
        foreach ($ads as $ad) {
            $ad->incrementViewCount();
        }
        
        // 格式化广告数据
        $formattedAds = [];
        foreach ($ads as $ad) {
            $formattedAds[] = [
                'id' => $ad->id,
                'title' => $ad->title,
                'image' => $ad->image,
                'url' => $ad->url,
                'position' => $ad->position,
                'position_name' => $ad->getPositionName()
            ];
        }
        
        return response()->json([
            'code' => 200,
            'data' => [
                'ads' => $formattedAds,
                'ad_enabled' => count($formattedAds) > 0
            ]
        ]);
    }
    
    /**
     * 跟踪广告事件（点击、展示等）
     */
    public function trackEvent(Request $request)
    {
        $this->validate($request, [
            'ad_id' => 'required|integer',
            'event_type' => 'required|string|in:click,view,impression'
        ]);
        
        $adId = $request->input('ad_id');
        $eventType = $request->input('event_type');
        
        // 查找广告
        $ad = Ad::find($adId);
        if (!$ad) {
            return response()->json([
                'code' => 404,
                'message' => '广告不存在'
            ]);
        }
        
        // 根据事件类型更新相应计数
        if ($eventType == 'click') {
            $ad->incrementClickCount();
            
            // 调用外部广告API记录点击事件（如果有）
            if (env('AD_API_URL')) {
                try {
                    $client = new Client();
                    $client->post(env('AD_API_URL') . '/track', [
                        'headers' => [
                            'Authorization' => 'Bearer ' . env('AD_API_KEY')
                        ],
                        'json' => [
                            'ad_id' => $adId,
                            'event' => $eventType,
                            'timestamp' => time(),
                            'user_agent' => $request->header('User-Agent')
                        ]
                    ]);
                } catch (\Exception $e) {
                    // 记录错误但不影响返回
                    // 实际项目中应该记录到日志系统
                }
            }
        } elseif ($eventType == 'view' || $eventType == 'impression') {
            $ad->incrementViewCount();
        }
        
        return response()->json([
            'code' => 200,
            'message' => '事件跟踪成功'
        ]);
    }
    
    /**
     * 获取广告列表（管理接口）
     */
    public function getAds(Request $request)
    {
        // 这里可以添加管理权限验证
        // 暂时简化处理
        
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 20);
        
        $query = Ad::query();
        
        // 搜索条件
        if ($title = $request->input('title')) {
            $query->where('title', 'like', '%' . $title . '%');
        }
        
        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }
        
        if ($position = $request->input('position')) {
            $query->where('position', $position);
        }
        
        $total = $query->count();
        $ads = $query->orderBy('display_order', 'asc')
            ->orderBy('id', 'desc')
            ->skip(($page - 1) * $pageSize)
            ->take($pageSize)
            ->get();
        
        // 格式化数据
        $formattedAds = [];
        foreach ($ads as $ad) {
            $formattedAds[] = [
                'id' => $ad->id,
                'title' => $ad->title,
                'image' => $ad->image,
                'url' => $ad->url,
                'position' => $ad->position,
                'position_name' => $ad->getPositionName(),
                'display_order' => $ad->display_order,
                'status' => $ad->status,
                'status_name' => $ad->status == Ad::STATUS_ENABLED ? '启用' : '禁用',
                'start_time' => $ad->start_time,
                'end_time' => $ad->end_time,
                'click_count' => $ad->click_count,
                'view_count' => $ad->view_count,
                'ctr' => $ad->view_count > 0 ? round(($ad->click_count / $ad->view_count) * 100, 2) : 0
            ];
        }
        
        return response()->json([
            'code' => 200,
            'data' => [
                'ads' => $formattedAds,
                'total' => $total,
                'page' => $page,
                'page_size' => $pageSize
            ]
        ]);
    }
}